<?php
// +----------------------------------------------------------------------
// | VueAdmin框架[基于ThinkPHP5开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2018 http://www.vueadmin.org
// +----------------------------------------------------------------------
// | VueAdmin承诺基础框架永久免费开源，您可用于学习和商用，但必须保留软件版权信息。
// +----------------------------------------------------------------------
// | Author: sept <917088650@qq.com>，开发者QQ群：63131383
// +----------------------------------------------------------------------

namespace app\system\middleware;


use app\lib\exception\ApiException;
use app\lib\returnCode\Code;
use app\lib\returnCode\Msg;
use app\system\controller\Token;
use app\system\model\AdminMenu as MenuModel;
use app\system\model\AdminRole;
use think\Controller;

class Auth extends Controller
{
    public function handle($request, \Closure $next)
    {
        $token = $request->header('token','');

        //验证Token是否正确
        $res = Token::check($token);

        if (is_object($res)) {
            //快过期的值加入到缓存中,用于过期刷新token
            $cache_token = cache('Login:'.$res->id);
            if ($token === $cache_token) {
                if (($res->user->exp - 3600) <= time()) {
                    //token还有一个小时过期,刷新token
                    //获取token
                    $newtoken = Token::access_token(['id'=>$res->id,'user'=>$res->user]);

                    cache('Login:'.$res->id,$newtoken);

                    return $this->success([
                        'access_token' => $newtoken,
                        'expires_in' => 7200,
                        'request_in' => \request()->time(),
                    ]);
                }

            } else {
                throw new ApiException(Code::SYSTEM_TOKEN_VALIDATION_FAILED,Msg::SYSTEM_TOKEN_VALIDATION_FAILED);
            }

            //加入当前登录用户信息到Auth对象中用于后续直接调用
            \app\lib\Auth\Auth::setAuth($res);

            //权限验证
            $c_menu = MenuModel::getInfo();

            AdminRole::checkAuth($c_menu['id']);

            return $next($request);
        }

        //token 验证失败
        throw new ApiException(Code::SYSTEM_TOKEN_VALIDATION_FAILED,Msg::SYSTEM_TOKEN_VALIDATION_FAILED);
    }


}
